package com.summer.threadSwitch;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.summer.threadSwitch.ThreadSwitch.Func;

public class SummerThreadFactory {
	
	public  static final SummerThreadFactory factory = new SummerThreadFactory();
//	private static final ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
	
	private SummerThreadFactory(){}
	
	public Future<?> buildSyn(Func<?> func){
		return new SummerFutureTask<>(func);
	}
	
	public Future<?> buildAsyn(Func<?>  func){
//		return new SummerFutureTask<>(func,service);
		return new SummerFutureTask<>(func,null);
	}
	
	
	public class SummerFutureTask<R> extends FutureTask<R>{
		
		private ScheduledExecutorService service = null;
		
		public SummerFutureTask(Func<R> func){
			super(new SummerCallable<R>(func));
			callSyn();
		}
		
		public SummerFutureTask(Func<R> func,ScheduledExecutorService service){
			super(new SummerCallable<R>(func));
			this.service = service;
			callAsyn();
		}
		
		public void callSyn(){
			run();
		}
		
		public void callAsyn(){
			new Thread(this).start();
		}
		
//		public Future<R> call(){
//			if(service==null)
//				this.run();
//			else {
//				service.schedule(this, 0, TimeUnit.SECONDS);
//			}
//			return this;
//		}
		
	}
	
	public class SummerCallable<R> implements Callable<R>{
		final Func<R> func;
		public SummerCallable(Func<R> func){
			this.func = func;
		}
		
		@Override
		public R call() throws Exception {
			return func.call();
		}
		
	}
}
